<?php

namespace app\common\service;

/**
 * 极光服务
 * Class PushJiguangService
 * @package app\common\service
 */
class PushJiguangService
{
    /**
     * 极光appKey
     * @var mixed
     */
    private $appKey;

    /**
     * 极光masterSecret
     * @var mixed
     */
    private $masterSecret;

    public function __construct()
    {
        $this->appKey = config('push')['jiguang']['appKey'];
        $this->masterSecret = config('push')['jiguang']['masterSecret'];
    }

    /**
     * 推送
     * https://docs.jiguang.cn/jpush/server/push/rest_api_v3_push/#_6
     * @param array $message 自定义消息
     * @param array $notification 通知
     * @param array $platform 推送平台 默认全部平台
     * @param array $audience 推送目标 默认全部目标，即广播
     * @param array $inappMessage 应用内提醒
     * @param array $smsMessage 短信补充
     * @param array $options 可选参数
     * @param array $callback 回调参数
     * @return array[]|bool|mixed|string 如果返回有参数 error 即是失败，用isset($res['error'])判断
     */
    public function push(
        array $message = [],
        array $notification = [],
        array $platform = [],
        array $audience = [],
        array $inappMessage = [],
        array $smsMessage = [],
        array $options = [],
        array $callback = []
    ) {
        $url = 'https://api.jpush.cn/v3/push';
        $header[] = 'accept: application/json';
        $header[] = 'Authorization: Basic ' . base64_encode("$this->appKey:$this->masterSecret");

        if (empty($notification) && empty($message)) {
            return ['error' => ['code' => 1002, 'message' => 'message和notification至少要有一个']];
        }

        if (!empty($platform)) {
            $param['platform'] = $platform;
        } else {
            $param['platform'] = 'all'; // 默认全平台
        }

        if (!empty($audience)) {
            $param['audience'] = $audience;
        } else {
            $param['audience'] = 'all'; // 默认全部目标，即广播
        }

        if (!empty($message)) {
            $param['message'] = $message;
        }

        if (!empty($notification)) {
            $param['notification'] = $notification;
        }

        if (!empty($inappMessage)) {
            $param['inapp_message'] = $inappMessage;
        }

        if (!empty($smsMessage)) {
            $param['sms_message'] = $smsMessage;
        }

        if (!empty($options)) {
            $param['options'] = $options;
        }

        if (!empty($callback)) {
            $param['callback'] = $callback;
        }

        $cidArr = $this->getPushCid();
        if (isset($cidArr['error'])) {
            lo($cidArr);
            return $cidArr;
        } else {
            $param['cid'] = $cidArr['cidlist'][0];
        }

        return curl_post($url, json_encode($param), $header);
    }

    /**
     * 获取唯一推送标识符cid
     * 可选，用于防止 api 调用端重试造成服务端的重复推送而定义的一个标识符
     * @param int $count 默认获取一个
     * @return bool|mixed|string
     */
    private function getPushCid(int $count = 1)
    {
        $url = 'https://api.jpush.cn/v3/push/cid?count=' . $count . '&type=push';
        $header[] = 'accept: application/json';
        $header[] = 'Authorization: Basic ' . base64_encode("$this->appKey:$this->masterSecret");

        return curl_get($url, [], $header);
    }

    /**
     * 通知消息
     * @param array $notification
     * @param array $registrationIds
     * @return array[]|bool|mixed|string
     */
    public function notificationPush(array $notification = [], array $registrationIds = [])
    {
        $notificationMsg = [
            'android' => [
                'title' => $notification['title'],
                'alert' => $notification['content'],
                'extras' => [
                    'data' => [
                        'route' => $notification['route'],
                        // 跳转 => event-push-jump，不跳 => event-push
                        'event' => $notification['event'],
                    ],
                ],
            ],
            'ios' => [
                'alert' => (string)$notification['content'],
                'content-available' => true,
                'mutable-content' => true,
                'extras' => [
                    'data' => [
                        'route' => $notification['route'],
                        'event' => $notification['event'],
                    ],
                ],
            ],
        ];
        $options = [
            'apns_production' => isset( $notification['apns_production'] ) ? $notification['apns_production'] : true,
        ];
        return $this->push([], $notificationMsg, [], ['registration_id' => $registrationIds], [], [], $options);
    }

    /**
     * 语聊事件推送
     * @param string $event 事件
     * @param array $registrationIds 注册ID数组
     * @param array $data 事件数据
     * @return array[]|bool|mixed|string
     */
    public function messageEventPush(string $event, array $registrationIds, array $data = [])
    {
        $content['message'] = 'msg';
        $content['event'] = $event;
        $content['data'] = $data;
        $content['title'] = 'event';
        $content['content_type'] = 'text';
        $msg['msg_content'] = $content;
        $msg['content_type'] = 'text';
        $msg['title'] = 'event';
        $audience['registration_id'] = $registrationIds;

        return $this->push($msg, [], [], $audience);
    }

}